'use client';
import { useClientParams, useGlobalState } from '@/hooks';
import Image from 'next/image';
import Link from 'next/link';
import './NoProductsFound.scss';
import { useEffect, useRef, useState } from 'react';
import { getProductsCount } from '@/services/front';

const defaultImg = (color: string = '#942FFB') =>
  `data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><rect width='100' height='100' fill='%23${color.replace(/#/g, '')}'/></svg>`;

const NoProductsFound = () => {
  const { categoryObject, categoryList } = useClientParams();

  const basePromotions: any[] = [
    {
      title: 'Baby & Kids',
      path: '/baby-kids',
      category_id: 810,
      image: defaultImg(),
    },
    {
      title: 'Sports & Fitness',
      path: '/sports-fitness',
      category_id: 1393,
      image: defaultImg(),
    },
    {
      title: 'Furniture',
      path: '/furniture',
      category_id: 971,
      image: defaultImg(),
    },
    {
      title: 'Pet Care',
      path: '/pet-care',
      category_id: 1336,
      image: defaultImg(),
    },
    {
      title: 'Shop All Promotions',
      path: '',
      category_id: null,
      image: defaultImg(),
    },
  ];

  //=======================================================================
  const [promotions, setPromotions] = useState<any[]>([]);
  const { isLogin } = useGlobalState('main');
  const initPromotions = (counts: any[]) => {
    const promotionsList = basePromotions.filter(
      (prom: any) =>
        !prom.category_id ||
        !!counts.find(
          (ct: any) => ct.category_id == prom.category_id && ct.count > 0
        )
    );
    promotionsList.forEach((prom: any) => {
      if (!prom.category_id) return;
      const findCat = categoryList?.find(
        (cat: any) => cat.category_id == prom.category_id
      );
      if (findCat?.image) prom.image = findCat?.image;
      else prom.image = defaultImg('#CFCCCF');
    });
    setPromotions(promotionsList);
  };
  const queryCounts = async () => {
    if (isLogin) {
      const queryParams = { on_promotion: true };
      const counts = await getProductsCount(queryParams).catch(e => {
        void e;
      });
      initPromotions(counts || []);
    }
  };
  const queryCountsRef = useRef(queryCounts);
  queryCountsRef.current = queryCounts;
  useEffect(() => {
    queryCountsRef.current();
  }, []);

  return (
    <div className="noproducts-wrapper">
      <div className="noproducts-title">No Products Found</div>
      <div className="noproducts-description">
        {`It looks like the filters you've selected didn't match any products in this category.`}
      </div>
      {isLogin && (
        <div className="noproducts-recommend">
          <div className="noproducts-recommend-title">Shop Promotions</div>
          <div className="noproducts-recommend-list">
            {promotions.map((p: any, idx: number) => (
              <div
                key={'K' + p.category_id}
                className="noproducts-recommend-list-item"
              >
                <Link href={`/promotion${p.path}`}>
                  <div className="noproducts-recommend-list-image-wrapper">
                    <Image
                      fill={true}
                      sizes={'160px'}
                      priority={true}
                      src={p.image}
                      alt={''}
                      className="noproducts-recommend-list-image"
                    />
                    {!p.category_id && (
                      <div className="noproducts-recommend-list-image-tips">
                        Shop All Promotions
                      </div>
                    )}
                  </div>
                  <p className="noproducts-recommend-list-name text-overflow-1">
                    {p.title}
                  </p>
                </Link>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default NoProductsFound;
